#
# "@(#) $Id: StatusPlayerProgressView.py,v 1.1.1.1 2006-07-27 03:16:08 gioshe Exp $"
#
# This work is released under the GNU GPL, version 2 or later.
#
from Utils.kdeemul import *
from Utils.human import *
from StatusSeekableProgressBar import *
from PixmapPushButton import *
from Player import *
from Utils.utils import *


class TimeLabel(QLabel):
	def __init__(self,text,parent):
		QLabel.__init__(self,text,parent)
		self.font=QFont()
		self.font.setPointSize(11)
		self.setFont(self.font)
		self.mode = "elapsed"
		self.current = 0
		self.total = 0
		self.isStream = False
		self.modes = {'elapsed':'remaining','remaining':'total','total':'elapsed'}
	
	def reset(self):
		self.mode = 'elapsed'
		self.load()

	def mouseReleaseEvent(self,event):
		if self.isStream:
			self.mode = 'elapsed'
		else:
			self.mode = self.modes[self.mode]
		self.load()
		
	def progress(self,current,total,isStream):
		self.current = current
		self.total = total
		self.isStream = isStream
		self.load()
	
	def load(self):
		if self.mode=='elapsed':
			self.doSetText(unikode(i18n('%s')) % humanDuration(self.current))
		elif self.mode=='remaining':
			self.doSetText(unikode(i18n('%s')) % humanDuration(self.total-self.current))
		elif self.mode=='total':
			self.doSetText(unikode(i18n('%s')) % humanDuration(self.total))
		else:
			self.doSetText('')
	
	def doSetText(self,text):
		if text!=unikode(self.text()):
			self.setText(text)



class ArtworkLabel(QWidget):

        _validExtensions = ['.jpg','.png']

        def __init__(self,container,name="ArtworkLabel",parent=None):
                QWidget.__init__(self,container,name)
                #self.imgDrag=QImageDrag(self,'dragimg')
                #self.parent = parent
                self.container=container
                self.fullPixmap = None
                self.smallPixmap = None
                self.hasImage = False
                self.currentScale = 0
		self.setFixedHeight(37)
		self.setFixedWidth(37)
                self.setBackgroundMode(Qt.NoBackground)
                self.setSizePolicy(QSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed,True))
                self.track=None
		self.hide()

        def fetchArt(self,track):
		print "FETCHING ART"
		self.track=track
                data = self.track.getImage()
                if data != None:
			print "GOT IMAGE"
                        self.fullPixmap = QPixmap()
                        self.fullPixmap.loadFromData(data)
                        self.currentScale = 0
                        self.buildSmallPixmap()
                        self.hasImage = True
                        self.setEnabled(True)
                        self.default=False
                        #self.fullPixmap.setDragEnabled(True)
			if not self.isVisible(): self.show()
                else:
                        #self.setDefault()
			self.hide()
        #
        # build a scaled version of the full sized image and keep it
        # maintain the aspect ratio, and don't increase the size
        #
        def buildSmallPixmap(self):
                if self.fullPixmap:
                        pixSize = self.fullPixmap.size()
                        size = self.size()
                        width = pixSize.width()
                        height = pixSize.height()
                        if width==0: width = 1
                        if height==0: height = 1
                        scaleX = 1.0*size.width()/width
                        scaleY = 1.0*size.height()/height
                        scale = scaleX
                        if scaleX>scaleY:
                                scale = scaleY
                        if scale>1.0:
                                scale = 1.0
                        if scale != self.currentScale:
                                mat = QWMatrix()
                                mat.scale(scale,scale)
                                self.smallPixmap = self.fullPixmap.xForm(mat)
                                self.currentScale = scale
                else:
                        self.smallPixmap = QPixmap()
                self.repaint()

        def setDefault(self):
                if self.default!=True:
                        self.fullPixmap = QPixmap(art('artwork.png'))
                        self.buildSmallPixmap()
                        self.default=True

        #
        # paint the cached scaled image of the cover in the artwork area
        #
        # to avoid flicker, we've turned off erasing, so we're responsible for
        # clearing out the emptry areas around the picture
        #
        def paintEvent(self,e):
                p = QPainter()
                p.begin(self)
                p.setBrush(QColor(255,255,255))
                p.setPen(QColor(255,255,255))
                srcSize = self.smallPixmap.size()
                dstSize = self.size()
                posX = (dstSize.width()-srcSize.width())/2
                posY = (dstSize.height()-srcSize.height())/2
                bitBlt(self,QPoint(posX,posY),self.smallPixmap,self.smallPixmap.rect(),Qt.CopyROP)
                if posX:
                        r = QRect(0,0,posX,dstSize.height())
                        p.drawRect(r)
                        r = QRect(dstSize.width()-posX,0,posX,dstSize.height())
                        p.drawRect(r)
                if posY:
                        r = QRect(0,0,dstSize.width(),posY)
                        p.drawRect(r)
                        r = QRect(0,dstSize.height()-posY,dstSize.width(),posY)
                        p.drawRect(r)
                p.end()


class NameLabel(KSqueezedTextLabel):
	def __init__(self,parent):
		KSqueezedTextLabel.__init__(self,parent)
		self.font=QFont()
		self.font.setPointSize(12)
		self.font.setBold(True)
		self.setFont(self.font)
		self.lastText = ""
		self.mode = 'title'
		self.track = None
		self.timerDuration = 8000
		self.startTimer(self.timerDuration)
	
	def reset(self):
		self.mode = 'title'
		self.load()
		self.killTimers()
		self.startTimer(self.timerDuration)

	def timerEvent(self,event):
		self.advanceMode()
	
	def mouseReleaseEvent(self,event):
		self.advanceMode()
		self.killTimers()
		self.startTimer(self.timerDuration)
	
	def advanceMode(self):
		if self.track:
			if self.track.isStream and not self.track.lsongs:
				self.mode=='title'
			else:
				if self.mode=='title':
					if self.track.artist:
						self.mode = 'artist'
					elif self.track.album:
						self.mode = 'album'
				elif self.mode=='artist':
					if self.track.album:
						self.mode = 'album'
					else:
						self.mode = 'title'
				elif self.mode=='album':
					self.mode = 'title'
				pass
			self.load()

	def setTrack(self,track):
		self.track = track
		self.load()

	def getTitle(self):
		if self.track: return str.join("",[self.track.title,self.track.artist,self.track.album])
		else: return ""

	def load(self):
		text = ''
		if self.track:
			if self.mode=='title': text = self.track.title
			elif self.mode=='artist': text = self.track.artist
			elif self.mode=='album': text = self.track.album
		if text==None or text=='':
			text = i18n('Connecting')
		self.doSetText(text)

	def doSetText(self,text):
		if text!=self.lastText:
			self.setText(text)
			self.lastText = text

_offset_owner = None
_offset = 0
_ignoreSetValue=False
_sliderSize=200
class ProgressSlider(QSlider):
	
	def mousePressEvent(self,e):
		global _ignoreSetValue
		_ignoreSetValue=True
		print "pressed",e.x(),">",e.y()

	def mouseReleaseEvent(self,e):
		global _ignoreSetValue
		global _sliderSize
		#self.setValue(e.x()-10)
		#self.setValue(e.x()+20*(e.x()/_sliderSize-0.5))
		print self.value() *(self.totalTime/float(_sliderSize))
		if self.totalTime: Player.seek(self.value() *(self.totalTime/float(_sliderSize)))
		_ignoreSetValue=False
		print "released"
		
	def mouseMoveEvent(self,e):
		#global _ignoresetvalue
		#_ignoreSetValue=True
		#print self.value(),e.pos()
		print "moving",(20*(e.x()/float(_sliderSize)-0.5)),e.x()/float(_sliderSize)
		if (e.x()>0 and e.x()< _sliderSize): self.setValue(e.x()+20*(e.x()/float(_sliderSize)-0.5))
		#_ignoreSetValue=False
		
	def setValueCheck(self,int):
		global _ignoreSetValue
		if _ignoreSetValue: return
		else: self.setValue(int)
	'''
        def wheelEvent(self,e):
                global _offset_owner, _offset,_sliderSize
                if ( e.orientation() != self.orientation() and  not self.rect().contains(e.pos()) ):
                        return

                if (_offset_owner != self):
                        _offset_owner = self
                        _offset = 0
                _offset = _offset-e.delta()*max(self.pageStep(),self.lineStep())/120
                if (abs(_offset)<1):
                        return
                self.setValue( self.value() - int(_offset) )
                _offset = _offset-int(_offset)
                e.accept()
		if self.currentTime and self.totalTime: Player.seek((self.value() - int(_offset))*(self.currentTime/self.totalTime))
		print ((self.value() - int(_offset))*(self.totalTime/_sliderSize)),"<<SET"
		#Player.seek((self.value() - int(_offset))*self.ProgressSlider.getTotal())
	'''
        def progress(self,status):
		global _sliderSize
                state = status['Status']
                if state in ['Playing']:
                        self.currentTime = status['currentTime']
                        self.totalTime = status['totalTime']
                else:
                        self.currentTime = 0
                        self.totalTime = 0
		#self.currentTime,self.totalTime
                if self.totalTime>0:
                        self.setValueCheck(_sliderSize*self.currentTime/self.totalTime)
	def getTotal(self): return self.totalTime
	def getIngnoreSetValue(self): return self.ignoreSetValue

class StatusPlayerProgressView(QWidget):
	def __init__(self,container,statusView):
		QWidget.__init__(self,container)
		self.statusView = statusView
		self.backColor=QColor(Settings.settings().get('ColorR'),Settings.settings().get('ColorG'),Settings.settings().get('ColorB'))
		self.setPaletteBackgroundColor(self.backColor)
		self.track = None
		self.buildViews()
		QObject.connect(Player.singleton(),PYSIGNAL("playback_status"),self.progress)
	
	def buildViews(self):
		global _sliderSize
		self.ProgressSlider = ProgressSlider(Qt.Horizontal,self)
                self.ProgressSlider.setFixedWidth(_sliderSize)
                #self.ProgressSlider.setFixedHeight(45)

                self.setFixedHeight(45)
                self.ProgressSlider.setTracking(False)
                self.ProgressSlider.setRange(0,_sliderSize)
		#f = QFont("fixed",9)
		hlayout = QHBoxLayout(self)
		hlayout.addItem(QSpacerItem(1,1,QSizePolicy.Expanding,QSizePolicy.Fixed))
		vlayout = QVBoxLayout()
		vlayout.setSpacing(-5)
		self.title = NameLabel(self)
		self.title.setText("Song Name")
		self.title.setAlignment(Qt.AlignLeft)
		self.artwork=ArtworkLabel(self)
		vlayout.addWidget(self.title)
		self.elapsed = TimeLabel(i18n("Elapsed Time"),self)
		self.elapsed.setAlignment(Qt.AlignCenter)
		playout = QHBoxLayout()
		hlayout.addLayout(playout)
		hlayout.addLayout(vlayout,100)
		#self.progressBar = SeekableStatusProgressBar(self)
		#QObject.connect(self.progressBar,PYSIGNAL("seeked"),self.doSeek)
		#playout.addItem(QSpacerItem(1,1,QSizePolicy.Expanding,QSizePolicy.Fixed))
		#playout.addWidget(self.progressBar,100)
		playout.addWidget(self.ProgressSlider,100)
		playout.addItem(QSpacerItem(10,1,QSizePolicy.Expanding,QSizePolicy.Fixed))
		playout.addWidget(self.elapsed)
		playout.addItem(QSpacerItem(40,1,QSizePolicy.Expanding,QSizePolicy.Fixed))
	 	playout.addWidget(self.artwork)	
		#self.artwork.setAlignment(Qt.AlignCenter)
		playout.addItem(QSpacerItem(20,1,QSizePolicy.Expanding,QSizePolicy.Fixed))
		#playout.addWidget(self.title,100)
		#playout.addItem(QSpacerItem(1,1,QSizePolicy.Expanding,QSizePolicy.Fixed))
		self.currentSong = KSqueezedTextLabel(self)
		self.currentSong.setText("")
		self.currentSong.setAlignment(Qt.AlignCenter)
		vlayout.addWidget(self.currentSong)
		self.currentSong.hide()
		bookmarkIcon = QIconSet(QPixmap(art("buttonstatusbookmark.png")))
		self.bookmarkButton = SmallPixmapPushButton(bookmarkIcon,"",self)
		QToolTip.add(self.bookmarkButton,i18n("Bookmark the current station"))
		QObject.connect(self.bookmarkButton,SIGNAL("clicked()"),self.bookmarkStream)
		hlayout.addWidget(self.bookmarkButton)
	
	def bookmarkStream(self):
		if self.track:
			self.track.bookmark()
			QMessageBox.information(None,i18n("Station Bookmarked"),i18n("The currently playing station has been bookmarked"))

	def progress(self,status):
		#return
		self.ProgressSlider.progress(status)
		state = status['Status']
		if state=='Begin':
			#print "player status got begin"
			self.elapsed.reset()
			self.elapsed.setText('')
			self.statusView.showStatus(self)
			track = status['Track']
			self.track = track
			self.title.reset()
			self.title.setTrack(track)
			if track.isStream:#setHidden(track.isStream)
				self.ProgressSlider.hide()
			self.currentSong.setHidden(not track.isStream or track.lsongs)
			self.bookmarkButton.setHidden(True)
			self.artwork.fetchArt(status['Track'])	
		elif state=='Connecting':
			#print "player status got connecting"
			track = status['Track']
			self.currentSong.setText(track.location)
			self.statusView.showStatus(self)
			self.title.text = 'Connecting'
		elif state=='Playing':
			if (self.track!=status['Track']):
				self.artwork.fetchArt(status['Track'])	
				#self.title=self.title.getTitle()
			self.track=track = status['Track']
		
			self.title.setTrack(track)
			if track.isStream and not track.lsongs:
				try: self.currentSong.setText(status['Current Title'])
				except: pass
			self.elapsed.progress(status['currentTime'],status['totalTime'],track.isStream and not track.lsongs)
			self.bookmarkButton.setHidden(not track.isStream or track.genre==None or track.lsongs)
		elif state=='End':
			self.statusView.hideStatus(self)

